package com.ruoyi.app.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.app.annotation.AppSecurity;
import com.ruoyi.app.util.ReqMsg;
import com.ruoyi.app.util.RspMsg;
import com.ruoyi.bizsys.domain.RepaymentOrder;
import com.ruoyi.bizsys.service.IRepaymentOrderService;
import com.ruoyi.bizsys.utils.BizConstants;
import com.ruoyi.business.domain.TransferQueryReq;
import com.ruoyi.business.service.ITransferService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.StringUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: jamnsin
 * @Date: 2022/6/10 11:24
 */
@Slf4j
@RestController
@RequestMapping("/app/transfer")
public class TransferController extends BaseController {

    @Autowired
    IRepaymentOrderService repaymentOrderService;

    @Autowired
    ITransferService transferService;

    public static final String TRANSFER_FLAG_BIND_CARD = "bind_card";

    public static final String TRANSFER_FLAG_CARD_PAY = "card_pay";

    @AppSecurity
    @ApiOperation("查询交易结果")
    @PostMapping("/reference")
    @Log(title = "查询交易结果", businessType = BusinessType.GET)
    public RspMsg getWalletAccount(@RequestBody @Validated ReqMsg reqMsg) {

        TransferQueryReq transferQueryReq = JSON.parseObject(JSON.toJSONString(reqMsg.getData()), TransferQueryReq.class);
        String reference = transferQueryReq.getReference();

        String transferFlag = getTransferFlag(reference);

        JSONObject result = new JSONObject();
        result.put("transferFlag", transferFlag);

        if (StringUtils.equals(TRANSFER_FLAG_CARD_PAY, transferFlag)) {
            RepaymentOrder repaymentOrder = repaymentOrderService.getOne(new QueryWrapper<RepaymentOrder>().select("loan_serial_no").eq("pay_trans_serial_no", reference).last("limit 1"));
            if (repaymentOrder != null) {
                result.put("loanSerialNo", repaymentOrder.getLoanSerialNo());
            }
        }

        try {
            JSONObject apiResult = transferService.verifyTransaction(reference, transferFlag);
            if (apiResult == null) {
                result.put("status", "pending");
                return RspMsg.ok(result);
            } else {
                result.put("status", apiResult.getString("status"));
                // result.put("message", apiResult.getString("gateway_response"));
            }
        } catch (Exception e) {
            if (e instanceof BusinessException) {
                BusinessException be = (BusinessException) e;
                log.error("查询代扣交易失败，errMsg = {}", be.getDetails(), e);
            } else {
                log.error("查询代扣交易异常，errMsg = {}", e.getMessage(), e);
            }
            result.put("status", "pending");
        }

        return RspMsg.ok(result);
    }

    private String getTransferFlag(String reference) {
        if (StringUtils.indexOfAny(reference, BizConstants.PAY_TRANS_FLAG_DF, BizConstants.PAY_TRANS_FLAG_DF_WALLET) != -1) {
            return TRANSFER_FLAG_CARD_PAY;
        } else if (reference.indexOf(BizConstants.SERIALNO_SEPARATOR_FLAG) == -1) {
            return TRANSFER_FLAG_CARD_PAY;
        } else if (reference.indexOf(BizConstants.PAY_TRANS_FLAG_BIND_CARD) != -1) {
            return TRANSFER_FLAG_BIND_CARD;
        }
        return "";
    }
}
